package com.wanbatv.wanba.jianshencao.activity;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.wanbatv.wanba.jianshencao.R;
import com.wanbatv.wanba.jianshencao.util.AppUtil;
import com.wanbatv.wanba.jianshencao.util.Crypto;
import com.wanbatv.wanba.jianshencao.util.Util;
import com.wanbatv.wanba.jianshencao.util.WanbaMediaPlayer;
import com.wanbatv.wanba.jianshencao.utils.Product;
//import com.wanbatv.wanbaott.WanbaPlayer;
//import com.wanbatv.wanbaott.WanbaPlayerCallback;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

import cn.ffcs.itvpay.ItvPayTask;

/**
 * Created by ricardo on 2017/3/28.
 */
public class EpgActivity extends FullScreenActivity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener {
    private WebView web;
    private Intent intent;
    private boolean preview;
    private String previewhost;
    private WebSettings settings;
    private SurfaceView media;
    JSONArray zhifuArray =null;
    String orderInfo=null;
    public static boolean IS_DINGGOU =false;
    private final int MSG_HIDE=100;
    private final int MSG_DISPLAY=110;
    private final int MSG_CHANGE=111;
    private int TAG=1;
    private String MYURL="http://itv.100.ahct.lv1.vcache.cn/600/jianshencao/fubuxunlianjiaoxue_H264_16_9_1920_1080_6000000bps.TS";
    Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case MSG_DISPLAY:
                    Log.d("ricardo",media.getVisibility()+"=="+mediaPlayer);
                    if (mediaPlayer!=null&&media.getVisibility()==View.INVISIBLE){
                        Log.d("ricardo","xianshi");
                        media.setVisibility(View.VISIBLE);
                        media.bringToFront();
                        mediaPlayer.start();
                    }else if (mediaPlayer!=null&&media.getVisibility()==View.GONE){
                        Log.d("ricardo","gone");
                        media.setVisibility(View.VISIBLE);
                        media.bringToFront();
                        mediaPlayer.start();
                    }
                    RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
                    lp1.setMargins(154,65,533,286);
                    media.setLayoutParams(lp1);
                    break;
                case MSG_HIDE:
                    if (mediaPlayer!=null&&media.getVisibility()==View.VISIBLE){
                        Log.d("ricardo","visi");
                        media.setVisibility(View.GONE);
                        mediaPlayer.release();
                        web.bringToFront();
                    }else if (mediaPlayer!=null&&media.getVisibility()==View.INVISIBLE){
                        Log.d("ricardo","invisi");
                        mediaPlayer.release();
                    }else if (mediaPlayer!=null&&media.getVisibility()==View.GONE){
                        Log.d("ricardo","gonegone");
                        mediaPlayer.release();
                    }

                    break;

                case MSG_CHANGE:
                    if (mediaPlayer!=null&&media.getVisibility()==View.INVISIBLE){
                        Log.d("ricardo","change invisible");
                        media.setVisibility(View.VISIBLE);
                        media.bringToFront();
                        web.requestFocus();
                        mediaPlayer.reset();
                        try {
                            mediaPlayer.setDataSource(MYURL);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        mediaPlayer.prepareAsync();
                    }else if (mediaPlayer!=null&&media.getVisibility()==View.GONE){
                        Log.d("ricardo","change invisible");
                        media.setVisibility(View.VISIBLE);
                        media.bringToFront();
                        web.requestFocus();
                        mediaPlayer.reset();
                        try {
                            mediaPlayer.setDataSource(MYURL);
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                        mediaPlayer.prepareAsync();
                    }
                    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
                    lp.setMargins(59,55,630,323);
                    media.setLayoutParams(lp);
                    break;
            }
        }
    };
    private SurfaceHolder holder;
    private MediaPlayer mediaPlayer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_epg);
        web = ((WebView) findViewById(R.id.web));
        media = ((SurfaceView) findViewById(R.id.video));
        holder = media.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        dinggou();
        Log.d("ricardo","oncreate");
        intent = getIntent();
        preview = intent.getBooleanExtra("preview",false);
        if (preview){
            previewhost = intent.getStringExtra("previewhost");
            if (!TextUtils.isEmpty(previewhost)){
                EpgHost.url=previewhost;
            }
        }
        //media.startPlay("http://itv.100.ahct.lv1.vcache.cn/600/jianshencao/fubuxunlianjiaoxue_H264_16_9_1920_1080_6000000bps.TS");

        settings = web.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);

        if ("E8205".equals(AppUtil.getValue("STB.Model",this))){
            Log.d("ricardo","8205");
            web.loadUrl(EpgHost.url+"/wanbaepg/home.html");
        }else {
            Log.d("ricardo","wocao?"+AppUtil.STB.Model+AppUtil.STB.UserID);
           // web.loadUrl("file:///android_asset/hehe.html");
            web.loadUrl(EpgHost.url+"/wanbaepg/one_index.html");
        }
        web.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return super.shouldOverrideUrlLoading(view, url);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                if (url.contains("one_index.html")){
                    view.clearHistory();
                }
                super.onPageFinished(view, url);
            }
        });
        web.addJavascriptInterface  (new EpgJavaScript(),"wanba");
        web.setVerticalScrollBarEnabled(false);
        web.setHorizontalScrollBarEnabled(false);

    }



    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Log.d("ricardo",web.getUrl()+"@@");

       if (keyCode==KeyEvent.KEYCODE_BACK&&web.canGoBack()&&web.getUrl().contains("detail")){
           MYURL="http://itv.100.ahct.lv1.vcache.cn/600/jianshencao/fubuxunlianjiaoxue_H264_16_9_1920_1080_6000000bps.TS";
           Log.d("ricardo","back");
           web.goBack();
           return true;
       }else if (keyCode==KeyEvent.KEYCODE_BACK&&!web.getUrl().contains("detail")&&!AppUtil.STB.Model.equals("E8205")){
           Log.d("ricardo","finsi");
           if (mediaPlayer!=null){
               mediaPlayer.release();
               mediaPlayer=null;
           }
           finish();
           return true;
       }else if(keyCode==KeyEvent.KEYCODE_BACK&&AppUtil.STB.Model.equals("E8205")&&web.canGoBack()&&web.getUrl().contains("subpage")){
           Log.d("ricardo","backqqq");
           web.goBack();
           return true;
       }else if(keyCode==KeyEvent.KEYCODE_BACK&&AppUtil.STB.Model.equals("E8205")&&!web.getUrl().contains("subpage")){
           Log.d("ricardo","backwww");
           if (mediaPlayer!=null){
               mediaPlayer.release();
               mediaPlayer=null;
           }
           finish();
           return true;
       }
        return super.onKeyDown(keyCode, event);
    }

    private void chanpinbao(){
        RequestQueue rq_2 = Volley.newRequestQueue(getApplicationContext());
        final JsonObjectRequest request_2 = new JsonObjectRequest("http://61.191.46.214:8087/getapi/common/subjects/31259d2c48bec6a1ba589360c748e132?flavor="+ Product.flavor, null,
                new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject jsonObject) {
                        try {
                            JSONObject obj=jsonObject.getJSONObject("data");
                            JSONArray arr=obj.getJSONArray("list");
                            zhifuArray =arr;
                            //Toast.makeText(getApplicationContext(),obj+"@@",Toast.LENGTH_LONG).show();
                            dingdanhao();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getApplicationContext(),"请求产品包超时，请检查网络并返回重试。",Toast.LENGTH_SHORT).show();

            }
        }

        ) {
            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String, String> headers = new HashMap<String, String>();
                PackageInfo pi= null;
                try {
                    pi = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0);
                    headers.put("accept", "applicationnd.wanba.wanbatv.com.wudao;version="+pi.versionName);
                    headers.put("app_version", pi.versionName);
                    headers.put("app_package_name",pi.packageName);
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }


                // MyLog.d(TAG, "headers=" + headers);
                return headers;
            }
        };
        request_2.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));

        rq_2.add(request_2);
    }
    private  void dingdanhao(){

        try {
            JSONObject obj = zhifuArray.getJSONObject(0);
            final   String subject=obj.getString("subject");
            final   String subjectId=obj.getString("subjectId");
            final   String price=obj.getString("price");
            //Toast.makeText(getApplicationContext(),obj+"==",Toast.LENGTH_SHORT).show();
            RequestQueue requestQueue = Volley.newRequestQueue(EpgActivity.this);
            String url="http://61.191.46.214:8087/postapi/common/wpay/getorder";
            StringRequest stringRequest = new StringRequest(com.android.volley.Request.Method.POST,url,
                    new Response.Listener<String>() {

                        @Override
                        public void onResponse(String response) {

                            try {

                                JSONObject objZhifubao = (JSONObject) new JSONTokener(response).nextValue();
                                //Toast.makeText(getApplicationContext(),obj_zhifubao+"  @  @  "+Util.getDeviceId(getApplicationContext()),Toast.LENGTH_LONG).show();
                                JSONObject oobj=objZhifubao.getJSONObject("data");
                                String order=oobj.getString("order");
                                orderInfo="orderId="+order+"|itvAccount="+ AppUtil.STB.UserID+"|productId=zg_wanba"+"|price=1500";
                                orderInfo=jiami(orderInfo);
                                Log.d("@ricardo@", "get subject "+objZhifubao);
                                ItvPayTask itvPayTask = new ItvPayTask(EpgActivity.this);
                                HashMap<String, String> data = new HashMap<String, String>();
                                data.put(ItvPayTask.NET_IP, "61.191.45.118");//访问地址ip 测试ip为61.191.45.116 正式为//61.191.45.118
                                data.put(ItvPayTask.NET_PORT, "7002");//访问地址端口
                                data.put(ItvPayTask.DEVICEMODEL, AppUtil.STB.Model);//机顶盒信息
                                //	data.put(ItvPayTask.RETURNURL, "http://61.191.46.214:8087/getapi/common/wpay/result/ahpay/");//同步返回地址
                                data.put(ItvPayTask.NOTIFYURL, "http://172.16.33.228:8087/postapi/common/wpay/paynotify/ahpay/"+AppUtil.STB.UserID);//异步通知地址
                                data.put(ItvPayTask.DEVICETYPE, "hd");//机顶盒信息
                                data.put(ItvPayTask.USERAGENT, "wanba");//机顶盒信息
                                data.put(ItvPayTask.DEVICESERIALNO, AppUtil.STB.Sn);//机顶盒信息
                                data.put(ItvPayTask.IP, AppUtil.STB.IP);//机顶盒信息
                                data.put(ItvPayTask.ORDERINFO, orderInfo);//订单信息
                                data.put(ItvPayTask.PROVIDERID, "shzg");//供应商id
                                itvPayTask.pay(data);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(getApplicationContext(),"请求订单号超时，请检查网络并返回重试。",Toast.LENGTH_SHORT).show();

                    error.printStackTrace();
                }
            }) {
                @Override
                public Map<String, String> getHeaders() throws AuthFailureError {
                    HashMap<String, String> headers = new HashMap<String, String>();
                    PackageInfo pi= null;
                    try {
                        pi = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0);
                        headers.put("accept", "applicationnd.com.wanbatv.wanba.jianshencao;version="+pi.versionName);
                        headers.put("app_version", pi.versionName);
                        headers.put("app_package_name",pi.packageName);
                    } catch (PackageManager.NameNotFoundException e) {
                        e.printStackTrace();
                    }


                    // MyLog.d(TAG, "headers=" + headers);
                    return headers;
                }
                @Override
                public String getBodyContentType() {
                    return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
                }
                @Override
                protected Map<String, String> getParams() {
                    //在这里设置需要post的参数
                    HashMap<String, String> params = new HashMap<String, String>();
                    params.put("partner","");
                    params.put("subject", subject);
                    params.put("subjectid",subjectId);
                    params.put("price",price);
                    params.put("provider","ahpay");
                    params.put("stb", Util.getDeviceId(getApplicationContext()));
                    params.put("flavor", Product.flavor);

                    return params;
                }
            };
            stringRequest.setRetryPolicy(new DefaultRetryPolicy(30000,3,1.0f));
            requestQueue.add(stringRequest);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    private  String jiami(String orderInfo){

        String jiami= Crypto.TripleDES.encrypt(orderInfo, "26f545c0d092463185acdd3e2c73fdda");
//        String jiami=Crypto.TripleDES.decrypt(jiami,"36161889369a412b923af17dafb0fe88");
        Log.e("jiami",jiami);
//        Log.e("jiemi",jiemi);
        return jiami;
    }
    private void dinggou(){

        String infoEncrypt = "itvAccount="+AppUtil.STB.UserID+"|"+"productId=zg_wanba";
        String orderInfo=jiami(infoEncrypt);

        try {
            orderInfo= URLEncoder.encode(orderInfo,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String url="http://61.191.45.118:7002/itv-api"+"/has_order?providerId="+"shzg"+"&orderInfo="+orderInfo;
        RequestQueue rq = Volley.newRequestQueue(EpgActivity.this.getApplicationContext());
        StringRequest request=new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.e("response:",response);
                try {
                    JSONObject obj = new JSONObject(response);
                    int num=obj.getInt("ordered");
                    if(num!=0){
                        IS_DINGGOU =true;
                    }else {
                        IS_DINGGOU =false;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                error.printStackTrace();
            }
        });
        rq.add(request);


    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setDisplay(holder);
            mediaPlayer.setDataSource(MYURL);
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(this);
            mediaPlayer.setOnCompletionListener(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i1, int i2) {

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {

    }

    @Override
    public void onPrepared(MediaPlayer mediaPlayer) {
        mediaPlayer.start();
    }

    @Override
    public void onCompletion(MediaPlayer mediaPlayer) {

    }


    public class EpgJavaScript{


        @JavascriptInterface
        public void conLog(String name){
            Log.d("ricardo",name);
        }
        @JavascriptInterface
        public void toMediaPlay(String url,String[] playurl,String[] img,String[] txt){
            if (mediaPlayer!=null) {
                Log.d("ricardo", "release");
                mediaPlayer.release();
                mediaPlayer=null;
            }
                Intent intent = new Intent(getApplicationContext(), ShowActivity.class);
                intent.putExtra("playurl",url);
                intent.putExtra("img",img);
                intent.putExtra("url",playurl);
                intent.putExtra("name",txt);
                startActivity(intent);


        }
        @JavascriptInterface
        public void isHome(String url){
            Log.d("ricardo","ishome");
            MYURL = url;
            handler.sendEmptyMessageDelayed(MSG_DISPLAY,1000);
        }
        @JavascriptInterface
        public void noHome(){
            Log.d("ricardo","nohome");
            handler.removeMessages(MSG_DISPLAY);
            handler.sendEmptyMessage(MSG_HIDE);
        }
        @JavascriptInterface
        public void isDetail(String url){
            Log.d("ricardo","isdetail");
            MYURL = url;
            handler.removeMessages(MSG_DISPLAY);
            handler.removeMessages(MSG_HIDE);
            handler.sendEmptyMessage(MSG_CHANGE);
        }
    }

    @Override
    protected void onDestroy() {
        if (mediaPlayer!=null){
            mediaPlayer.release();
            mediaPlayer=null;
        }
        super.onDestroy();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d("ricardo","onstart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d("ricardo","onresume");
        if (mediaPlayer==null){
            mediaPlayer=new MediaPlayer();
        }
    }



    @Override
    protected void onStop() {
        Log.d("ricardo","onstop");
        if (mediaPlayer!=null){
            Log.d("ricardo","stoprelease");
            mediaPlayer.release();
            mediaPlayer=null;
        }
        super.onStop();
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ItvPayTask.REQUEST_ITYPAY&&resultCode==ItvPayTask.RESULT_ITVPAY) {
            String result = data.getStringExtra("result");
            //Toast.makeText(getApplicationContext(),result+"",Toast.LENGTH_LONG).show();
            //Log.d("ricardo@@",data.getStringExtra("providerId"));
            try {
                JSONObject obj=(JSONObject) new JSONTokener(result).nextValue();
                Log.d("ricardo@@@",obj+"");
                if(!obj.getString("tradeInfo").equals("") ){
                    IS_DINGGOU=true;
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.e("huidiao",result);
        }
    }
}
